import 'dart:convert';
import 'dart:ffi';
import 'dart:io';

import 'package:baselib/utils/file_util.dart';
import 'package:baselib/utils/image_util.dart';
import 'package:baselib/utils/keyboard_util.dart';
import 'package:baselib/utils/load_util.dart';
import 'package:baselib/utils/log_util.dart';
import 'package:baselib/utils/navigator_util.dart';
import 'package:baselib/utils/permissions_helper.dart';
import 'package:baselib/utils/toast_util.dart';
import 'package:baselib/widgets/comm_message_gradient_dialog.dart';
import 'package:baselib/widgets/comm_select_gradient_dialog.dart';
import 'package:baselib/widgets/comm_select_widget.dart';
import 'package:baselib/widgets/refresh_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:framelib/base/base_view_model.dart';
import 'package:framelib/config/api_config.dart';
import 'package:framelib/config/route_config.dart';
import 'package:framelib/net/baseentity.dart';
import 'package:framelib/utils/agora_sdk_util.dart';
import 'package:framelib/utils/color_util.dart';
import 'package:framelib/utils/drawable_util.dart';
import 'package:framelib/utils/nim_sdk_util.dart';
import 'package:framelib/utils/px_util.dart';
import 'package:framelib/utils/select_util.dart';
import 'package:framelib/utils/string_util.dart';
import 'package:framelib/widgets/chat_room_oper_widget.dart';
import 'package:framelib/widgets/chat_room_person_info_widget.dart';
import 'package:framelib/widgets/invite_onmic_gradient_dialog.dart';
import 'package:framelib/widgets/room_other_info_gradient_dialog.dart';
import 'package:framelib/widgets/room_self_info_gradient_dialog.dart';
import 'package:framelib/widgets/room_top_widget.dart';
import 'package:framelib/widgets/send_comment_widget.dart';
import 'package:module_business/module_comm/model/user_entity.dart';
import 'package:module_business/module_comm/model/user_params_model.dart';
import 'package:module_business/module_contact/service/module_contact_service.dart';
import 'package:module_business/module_contact/viewmodel/contact_view_model.dart';
import 'package:module_business/module_index/model/index_room_item_entity.dart';
import 'package:module_business/module_index/model/member_status_entity.dart';
import 'package:module_business/module_index/model/voice_person_entity.dart';
import 'package:module_business/module_index/service/module_index_service.dart';
import 'package:get/get.dart';
import 'package:module_business/module_my/service/module_my_service.dart';
import 'package:nim_core/nim_core.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:agora_rtc_engine/agora_rtc_engine.dart';
import 'package:image_picker/image_picker.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

class ChatRoomViewModel extends BaseViewModel<ModuleContactService> with GetTickerProviderStateMixin{
  ModuleContactService moduleContactService;
  ModuleIndexService moduleIndexService;
  ModuleMyService moduleMyService;
  // AutoScrollController autoController = AutoScrollController();
  RefreshController refreshController = RefreshController(initialRefresh: true);
  RefreshState loadStatus=RefreshState.OK;
  int page = 1;
  bool isCanMoreData = false;
  String yxRoomId='';
  String fromType='';
  TextEditingController commentController = TextEditingController();
  ScrollController commentScrollController = ScrollController();
  final ImagePicker _picker = ImagePicker();

  RxBool emojiSelected = false.obs;
  RxBool pictureSelected = false.obs;
  //关注的人列表
  List<String> myFollowIds =[];
  //黑名单列表
  List<String> myBlackIds =[];
  //云信房间信息
  Rx<NIMChatroomInfo> roomYxInfo = NIMChatroomInfo().obs;
  //聊天室聊天信息
  Rx<List<NIMChatroomMessage>> chatRoomMsgs = Rx<List<NIMChatroomMessage>>([]);
  //聊天室服务端成员信息
  List<UserEntity> chatRoomServiceMembers= [];
  //聊天室服务端成员云信id信息
  List<String> chatRoomServiceMembersAccIds= [];
  //聊天室成员信息
  List<NIMChatroomMember> chatRoomMembers= [];


  @override
  ModuleContactService createService(){
    moduleIndexService = ModuleIndexService();
    moduleMyService = ModuleMyService();
    return moduleContactService = ModuleContactService();
  }

  @override
  void onInit() {
    yxRoomId = (Get.arguments??{})['yxRoomId'];
    fromType = (Get.arguments??{})['fromType'];
    LogUtil.d('ChatRoomViewModel--->yxRoomId=$yxRoomId,fromType=$fromType,');
    // autoController = AutoScrollController(
    //   viewportBoundaryGetter: () => Rect.fromLTRB(0, 0, 0, MediaQuery.of(Get.context).padding.bottom),
    //   axis: Axis.vertical,
    // );
    super.onInit();
    //查询聊天室信息
    queryChatRoomInfo();
    //查询我的关注列表
    getMyFollows();
    //查询我的拉黑用户列表
    getMyBlacks();
    //设置消息监听
    _setLinsener();
  }
  @override
  void onClose() {
    if(commentController!=null)commentController.dispose();
    if(commentScrollController!=null)commentScrollController.dispose();
    // if(autoController!=null)autoController.dispose();
    logOutChatRoom();
    super.onClose();
  }
  _setLinsener(){
    NIMSDKUtil.instance.onChatroomServiceMessageReceivedListen((List<NIMChatroomMessage> chatRoomMessages){
      LogUtil.d('NIMSDKUtil--->onChatroomServiceMessageReceivedListen');
      (chatRoomMessages??[]).forEach((element) {
        NIMMessageType messageType2 = element?.messageType;
        LogUtil.d('NIMSDKUtil--->notification messageType2=${messageType2}');
        if(NIMMessageType.notification == messageType2){
          var messageSubType = element?.messageSubType;
          NIMChatroomNotificationAttachment messageAttachment = element?.messageAttachment;
          LogUtil.d('NIMSDKUtil--->notification messageAttachment=${messageAttachment?.toMap()}');
          LogUtil.d('NIMSDKUtil--->notification messageAttachment type=${messageAttachment?.type}');
          // NIMChatroomNotificationAttachment
          //NIMChatroomMemberInAttachment
          switch (messageAttachment.type) {
            case NIMChatroomNotificationTypes.chatRoomMemberIn:
            //   attachmentMemberMessages.value.insert(0,MemberStatusEntity(
            //     fromAccount: element?.fromAccount,
            //     fromNickName: messageAttachment?.operatorNick,
            //     type: messageAttachment?.type,
            //   ));
            //查询聊天室信息
              queryChatRoomInfo();
              break;
            case NIMChatroomNotificationTypes.chatRoomMemberExit:
              // attachmentMemberMessages.value.insert(0,MemberStatusEntity(
              //   fromAccount: element?.fromAccount,
              //   fromNickName: messageAttachment?.operatorNick,
              //   type: messageAttachment?.type,
              // ));
            //查询聊天室信息
              queryChatRoomInfo();
              break;
            case NIMChatroomNotificationTypes.chatRoomMemberBlackAdd:
              break;
            case NIMChatroomNotificationTypes.chatRoomMemberBlackRemove:
              break;
            case NIMChatroomNotificationTypes.chatRoomMemberMuteAdd:
              break;
            case NIMChatroomNotificationTypes.chatRoomMemberMuteRemove:
              break;
            case NIMChatroomNotificationTypes.chatRoomManagerAdd:
              break;
            case NIMChatroomNotificationTypes.chatRoomManagerRemove:
              break;
            case NIMChatroomNotificationTypes.chatRoomCommonAdd:
              break;
            case NIMChatroomNotificationTypes.chatRoomCommonRemove:
              break;
            case NIMChatroomNotificationTypes.chatRoomClose:
              // attachmentMemberMessages.value.insert(0,MemberStatusEntity(
              //   fromAccount: element?.fromAccount,
              //   fromNickName: messageAttachment?.operatorNick,
              //   type: messageAttachment?.type,
              // ));
              break;
            case NIMChatroomNotificationTypes.chatRoomInfoUpdated:
              //更新房间信息
              queryChatRoomInfo();
              break;
            case NIMChatroomNotificationTypes.chatRoomMemberKicked:
              break;
            case NIMChatroomNotificationTypes.chatRoomMemberTempMuteAdd:
              break;
            case NIMChatroomNotificationTypes.chatRoomMemberTempMuteRemove:
              break;
            case NIMChatroomNotificationTypes.chatRoomMyRoomRoleUpdated:
              break;
            case NIMChatroomNotificationTypes.chatRoomQueueChange:
              break;
            case NIMChatroomNotificationTypes.chatRoomRoomMuted:
              break;
            case NIMChatroomNotificationTypes.chatRoomRoomDeMuted:
              break;
            case NIMChatroomNotificationTypes.chatRoomQueueBatchChange:
              break;
            default:
              break;
          }
        }
        else if(NIMMessageType.custom == messageType2){
          // element.remoteExtension
          // NIMChatroomNotificationAttachment messageAttachment = element?.messageAttachment;
          LogUtil.d('NIMSDKUtil--->notification element=${element?.toMap()}');
          var remoteExtensions = element?.remoteExtension;
          if((remoteExtensions!=null)&&(remoteExtensions is Map)){
            var remoteExtensionDatas = remoteExtensions['data'];
            if((remoteExtensionDatas!=null)&&(remoteExtensionDatas is List)){
              if(remoteExtensionDatas.length>0){
                // remoteExtensionDatas.forEach((remoteExte) {
                //   defaultPersons.forEach((defaultPerson) {
                //     if(remoteExte['mikeIndex'] == defaultPerson?.mikeIndex){
                //       defaultPerson.lockFlag = remoteExte['lockFlag'];
                //       defaultPerson.identityType = remoteExte['identityType'];
                //       defaultPerson.icon = remoteExte['icon'];
                //       defaultPerson.nickname = remoteExte['nickname'];
                //       defaultPerson.userId = remoteExte['userId'];
                //       defaultPerson.yxAccid = remoteExte['yxAccid'];
                //     }
                //   });
                // });
                // update();
              }
            }
          }
        }
      });
      setChatRoomMessages(messages: chatRoomMessages??[]);
    });
    NIMSDKUtil.instance.onCustomNotificationListen((CustomNotification event) {
      LogUtil.d('NIMSDKUtil--->  inviteOnMic onCustomNotification--->event=${event?.toMap()}');
      // if((event?.content??'').isNotEmpty){
      //   var contentTemp = json.decode(event?.content??'');
      //   if(contentTemp is Map){
      //     var notifyType = contentTemp['notifyType'];
      //     if(notifyType == 'invite_onmic'){
      //       //邀请上麦
      //       // {"attachType":-3,"notifyType":"invite_onmic","roomId":100,
      //       // "icon":"https://app-bucket-test.oss-accelerate.aliyuncs.com/ios/77985415/230305/u678994803_4000x3000_20230305194926.jpg",
      //       // "nickname":"lx","userId":1284,"yxAccid":"87118bd5619640f6a8c408533479d9a4"}
      //       var fromRoomId = contentTemp['roomId'];
      //       if(fromRoomId!=roomInfo?.id)return;
      //       var fromNickName = contentTemp['nickname'];
      //       var fromIcon = contentTemp['icon'];
      //       showDialog(
      //           context: Get.context,
      //           builder: (_){
      //             return InviteOnMicGradientDialog(
      //               message: '${fromNickName} ${StringUtil.instance.invites_you_to_on_mic}',
      //               icon: fromIcon,
      //               onPositivePressEvent: (){
      //                 Navigator.of(Get.context).pop();
      //
      //               },
      //               onCloseEvent: (){
      //                 LogUtil.d('showDialog-->onCloseEvent');
      //                 Navigator.of(Get.context).pop();
      //               },
      //             );
      //           }
      //       );
      //     }else if(notifyType=='kickOut'){
      //       isForceLeave = true;
      //       ToastUtil.toast(StringUtil.instance.You_are_forced_to_leave_the_room);
      //       if(isUpWheat(currVoicePersonEntity)){
      //         var currPersions = defaultPersons.where((element) => (element?.userId==currVoicePersonEntity?.userId)).toList();
      //         LogUtil.d('离开事件通知---->currPersions.isNotEmpty=${currPersions.isNotEmpty},');
      //         if(currPersions.isNotEmpty)downMic(currPersions[0]);
      //       }
      //       logOutChatRoom();
      //       NavigatorUtil.goBack();
      //     }
      //   }
      // }
    });
    NIMSDKUtil.instance.onChatroomServiceEventNotifiedListen((NIMChatroomEvent event){
      LogUtil.d('NIMSDKUtil--->onChatroomServiceEventNotifiedListen');
      if (event is NIMChatroomStatusEvent) {
        /// 连接状态事件通知
      }else if (event is NIMChatroomKickOutEvent) {
        /// 离开事件通知
        // nimChatroomKickOutEvent.value = event;
        NavigatorUtil.goBack();
        ToastUtil.toast(StringUtil.instance.You_are_forced_to_leave_the_room);
      }
    });
    NIMSDKUtil.instance.onChatroomServiceMessageStatusChangedListen((NIMChatroomMessage chatRoomMessage){
      LogUtil.d('NIMSDKUtil--->onChatroomServiceMessageStatusChangedListen');


    });
  }
  void logOutChatRoom() async{
    var nimResult = await NimCore.instance.chatroomService.exitChatroom(yxRoomId);
    if(nimResult?.isSuccess){
      LogUtil.d('logOutChatRoom--->退出聊天室成功');
    }
  }

  toRoomClose(){
    showDialog(
        context: Get.context,
        builder: (BuildContext context){
          return RoomTopWidget(
            onRoomClose: (){
              LogUtil.d('退出房间');
              NavigatorUtil.goBack();
              NavigatorUtil.goBack();
            },
          );
        }
    );
  }
  bool isOpenButtonUi() {
    return emojiSelected.value||pictureSelected.value;
  }

  emojiSelect() {
    emojiSelected.value=!(emojiSelected.value??false);
    pictureSelected.value = false;
  }
  pictureSelect() async{
    // pictureSelected.value=!(pictureSelected.value??false);
    pictureSelected.value= false;
    emojiSelected.value = false;
    //弹出选择图片
    if (await PermissionsHelper.requestPermission(Platform.isIOS ? [Permission.photos] : [Permission.storage])) {
      _pickImage();
    }
  }
  _pickImage() async {
    final List<XFile> pickedFileList = await _picker.pickMultiImage();
    if (pickedFileList != null) {
      for (XFile image in pickedFileList) {
        int len = await image.length();
        sendImageMessage(image.path, len);
      }
    }
  }
  void sendImageMessage(String filePath, int fileSize,) async{
    NIMResult<NIMChatroomMessage> createMsgResult =
    await ChatroomMessageBuilder.createChatroomImageMessage(
        roomId: yxRoomId, filePath: filePath,displayName: FileUtil.getFileName(filePath: filePath),
        nosScene: NIMNosScenes.defaultIm);
    if(!(createMsgResult?.isSuccess??false)){
      LoadUtil.hideLoad();
      ToastUtil.toast(StringUtil.instance.Send_fail);
      return;
    }
    createMsgResult?.data?.enableHistory = true;
    NIMResult<NIMChatroomMessage> sendMessageResult = await NimCore.instance.chatroomService.sendChatroomMessage(createMsgResult?.data);
    if(sendMessageResult?.isSuccess??false){
      chatRoomMsgs.value.add(sendMessageResult.data);
      chatRoomMsgs.refresh();
      if(!chatRoomServiceMembersAccIds.contains(sendMessageResult?.data?.fromAccount)){
        chatRoomServiceMembersAccIds.add(sendMessageResult?.data?.fromAccount);
        //获取服务端成员列表
        _getChatRoomServiceMembers();
      }
      /// 延迟500毫秒，再进行滑动
      // Future.delayed(Duration(milliseconds: 800), ()=>autoController.jumpTo(autoController?.position?.maxScrollExtent??0));
    }else{
      ToastUtil.toast(sendMessageResult?.errorDetails);
    }
  }
  /**
   * 发送消息
   */
  sendMsg() async{
    // isCommentOpen.value = false;
    if(commentController.text.isEmpty)return;
    // LoadUtil.showLoad(loadingText: '${StringUtil.instance.Send}...');
    NIMResult<NIMChatroomMessage> createMsgResult = await ChatroomMessageBuilder.createChatroomTextMessage(
      roomId: yxRoomId, text: commentController.text,);
    if(!(createMsgResult?.isSuccess??false)){
      // LoadUtil.hideLoad();
      ToastUtil.toast(StringUtil.instance.Send_fail);
      return;
    }
    createMsgResult?.data?.enableHistory = true;

    NIMResult<NIMChatroomMessage> sendMsgResult = await NimCore.instance.chatroomService.sendChatroomMessage(createMsgResult?.data);
    // LoadUtil.hideLoad();
    if(sendMsgResult?.isSuccess??false){
      // ToastUtil.toast(StringUtil.instance.Send_success);
      chatRoomMsgs.value.add(sendMsgResult.data);
      chatRoomMsgs.refresh();
      if(!chatRoomServiceMembersAccIds.contains(sendMsgResult?.data?.fromAccount)){
        chatRoomServiceMembersAccIds.add(sendMsgResult?.data?.fromAccount);
        //获取服务端成员列表
        _getChatRoomServiceMembers();
      }
      commentController.clear();
      /// 延迟500毫秒，再进行滑动
      // Future.delayed(Duration(milliseconds: 800), ()=>autoController.jumpTo(autoController?.position?.maxScrollExtent??0));
    }else{
      ToastUtil.toast(StringUtil.instance.Send_fail);
    }
  }

  void queryChatRoomInfo() async{
    LogUtil.d('queryChatRoomInfo--->yxRoomId=${yxRoomId}');
    NIMResult<NIMChatroomInfo>  fetchChatroomInfoResult =
            await  NimCore.instance.chatroomService.fetchChatroomInfo(yxRoomId);
    LogUtil.d('queryChatRoomInfo--->${fetchChatroomInfoResult?.toMap()}');
    if(fetchChatroomInfoResult?.isSuccess??false){
      roomYxInfo.value = fetchChatroomInfoResult.data;
      if((fromType??'').isEmpty)return;
      ContactViewModel contactViewModel = Get.find();
      if(fromType == StringUtil.instance.Sport){
        contactViewModel.sportChatRoomInfo.value = roomYxInfo.value;
      }else if(fromType == StringUtil.instance.Music){
        contactViewModel.musicChatRoomInfo.value = roomYxInfo.value;
      }else if(fromType == StringUtil.instance.Yoga){
        contactViewModel.yogaChatRoomInfo.value = roomYxInfo.value;
      }
    }
    //查询聊天室成员列表
    getMembers();
  }
  /**
   * 获取房间成员
   */
  void getMembers() async{
    // chatRoomMembers.clear();
    NIMResult<List<NIMChatroomMember>> allNormalMemberResult =
          await NimCore.instance.chatroomService.fetchChatroomMembers(
      roomId: yxRoomId,
      queryType: NIMChatroomMemberQueryType.allNormalMember,
      limit: 1000000,
    );
    int idsPreLength = chatRoomServiceMembersAccIds.length;
    if(allNormalMemberResult?.isSuccess){
      var results = allNormalMemberResult.data??[];
      if(results.isNotEmpty){
        results.forEach((element) {
          if(!chatRoomMembers.map((e) => e?.account).toList().contains(element)){
            chatRoomMembers.add(element);
          }
          if(!chatRoomServiceMembersAccIds.contains(element?.account)){
            chatRoomServiceMembersAccIds.add(element?.account);
          }
        });
      }
    }
    NIMResult<List<NIMChatroomMember>> onlineGuestMemberByEnterTimeDescResult
          = await NimCore.instance.chatroomService.fetchChatroomMembers(
      roomId: yxRoomId,
      queryType: NIMChatroomMemberQueryType.onlineGuestMemberByEnterTimeDesc,
      limit: 1000000,
    );
    if(onlineGuestMemberByEnterTimeDescResult?.isSuccess){
      var results = onlineGuestMemberByEnterTimeDescResult.data??[];
      if(results.isNotEmpty){
        results.forEach((element) {
          if(!chatRoomMembers.map((e) => e?.account).toList().contains(element)){
            chatRoomMembers.add(element);
          }
          if(!chatRoomServiceMembersAccIds.contains(element?.account)){
            chatRoomServiceMembersAccIds.add(element?.account);
          }
        });
      }
    }
    if(idsPreLength!=chatRoomServiceMembersAccIds.length){
      //获取服务端成员列表
      _getChatRoomServiceMembers();
    }
    update();
  }
  //获取服务端成员列表
  void _getChatRoomServiceMembers() async{
    // List<String> yxMembersIds = (chatRoomMembers??[]).map((e) => e?.account).toList();

    LogUtil.d('_getChatRoomServiceMembers--->chatRoomServiceMembersAccIds=$chatRoomServiceMembersAccIds');
    Map<String,dynamic> upData={
      // "roomId": yxRoomId,
      "roomId": 0,
      "yxAccids": chatRoomServiceMembersAccIds
    };
    BaseEntity baseEntity= await moduleIndexService.api_voicechat_room_queryOnlineUserInfo(parmsMap: upData);
    if(baseEntity?.code==ApiConfig.SUCCESS_CODE){
      List<UserEntity> dataTemps=baseEntity?.result??[];
      if(dataTemps.isNotEmpty){
        chatRoomServiceMembers.clear();
        chatRoomServiceMembers.addAll(dataTemps);
        update();
      }
    }
  }
  setChatRoomMessages({List<NIMChatroomMessage> messages,bool isInitData}) async {
    messages.forEach((element) {
      LogUtil.d('NIMSDKUtil--->recieve message=${element?.toMap()}');
    });
    if (messages.length > 0) {
      List<NIMChatroomMessage> successMessages = messages.where((element) =>
      element.status == NIMMessageStatus.success &&
          (element.messageType == NIMMessageType.image ||
              element.messageType == NIMMessageType.text)).toList();
      int idsPreLength = chatRoomServiceMembersAccIds.length;
      (successMessages??[]).forEach((element) {
        if(!chatRoomServiceMembersAccIds.contains(element?.fromAccount)){
          chatRoomServiceMembersAccIds.add(element?.fromAccount);
        }
      });
      if(idsPreLength!=chatRoomServiceMembersAccIds.length){
        //获取服务端成员列表
        _getChatRoomServiceMembers();
      }
      chatRoomMsgs.value.addAll(successMessages);
      chatRoomMsgs.refresh();
      /// 延迟500毫秒，再进行滑动
      // Future.delayed(Duration(milliseconds: 800), ()=>autoController.jumpTo(autoController?.position?.maxScrollExtent??0));
    }
  }
  //查询聊天室历史聊天记录
  onRefresh({int pageCur,}) async{
    if(pageCur!=null)page=pageCur;
    LogUtil.d('ChatRoomViewModel,yxRoomId--->$yxRoomId');
    NIMResult<List<NIMChatroomMessage>> historyMessages =
          await NimCore.instance.chatroomService.fetchMessageHistory(
            roomId: yxRoomId,
            startTime: DateTime.now().millisecondsSinceEpoch,
            limit: 100,
            direction: QueryDirection.QUERY_OLD,
            messageTypeList: [NIMMessageType.text,NIMMessageType.image],
          );
    if(refreshController!=null)refreshController.refreshCompleted();
    if(refreshController!=null)refreshController.loadComplete();
    LogUtil.d('ChatRoomViewModel,historyMessages--->${historyMessages?.toMap()}');
    LogUtil.d('ChatRoomViewModel,historyMessages--->isSuccess=${historyMessages?.isSuccess}');
    if(historyMessages?.isSuccess){
      loadStatus=RefreshState.OK;
      List<NIMChatroomMessage> messages= historyMessages?.data??[];
      //更新消息列表
      if (messages.length > 0) {
        List<NIMChatroomMessage> successMessages = messages.where((element) =>
        element.status == NIMMessageStatus.success &&
            (element.messageType == NIMMessageType.image ||
                element.messageType == NIMMessageType.text)).toList();
        int idsPreLength = chatRoomServiceMembersAccIds.length;
        (successMessages??[]).forEach((element) {
          if(!chatRoomServiceMembersAccIds.contains(element?.fromAccount)){
            chatRoomServiceMembersAccIds.add(element?.fromAccount);
          }
        });
        if(idsPreLength!=chatRoomServiceMembersAccIds.length){
          //获取服务端成员列表
          _getChatRoomServiceMembers();
        }
        chatRoomMsgs.value.clear();
        chatRoomMsgs.value.addAll(successMessages);
        chatRoomMsgs.value = chatRoomMsgs.value.reversed.toList();
      }
    }else{
      loadStatus=RefreshState.NET_ERROR;
    }
    chatRoomMsgs.refresh();
    /// 延迟500毫秒，再进行滑动
    // Future.delayed(Duration(milliseconds: 800), ()=>autoController.jumpTo(autoController?.position?.maxScrollExtent??0));
  }
  bool isFollow(UserEntity chatRoomServiceMember) {
    return myFollowIds.contains('${chatRoomServiceMember?.userId??(-1000)}');
  }
  bool isInBlackList(UserEntity chatRoomServiceMember) {
    return myBlackIds.contains('${chatRoomServiceMember?.userId??(-1000)}');
  }
  onPersonTap(NIMChatroomMessage msgDataItem,UserEntity chatRoomServiceMember) {
    // if(!(chatRoomServiceMembers.map((e) => e?.yxAccid)).contains(msgDataItem?.fromAccount))return;
    showModalBottomSheet(
        context: Get.context,
        isScrollControlled: true,
        backgroundColor: ColorUtil.instance.color_transparent,
        builder: (BuildContext context){
          return ChatRoomPersonInfoWidget(
            coverPath: chatRoomServiceMember?.icon,
            name: msgDataItem?.fromNickname,
            userId: chatRoomServiceMember?.userId,
            cancelText: isFollow(chatRoomServiceMember)?
                          StringUtil.instance.Unfollow:StringUtil.instance.Follow,
            onFollow: (){
              NavigatorUtil.goBack();
              startFollowOrUnfollow(msgDataItem,chatRoomServiceMember);
            },
            onPositivePressEvent: ()=>NavigatorUtil.goBack(),
            onPersonInfoPressed: (){
              NavigatorUtil.goBack();
              toPersonHome(chatRoomServiceMember?.userId);
            },
            onMorePressed: (){
              NavigatorUtil.goBack();
              showChatRoomPersonOper(msgDataItem,chatRoomServiceMember);
            },
          );
        }
    );
  }
  showChatRoomPersonOper(NIMChatroomMessage msgDataItem,UserEntity chatRoomServiceMember) {
    showModalBottomSheet(
        context: Get.context,
        isScrollControlled: true,
        backgroundColor: ColorUtil.instance.color_transparent,
        builder: (BuildContext context){
          return ChatRoomOperWidget(
            isInBlackList: isInBlackList(chatRoomServiceMember),
            reportSelectedFunc: (){
              LogUtil.d('showChatRoomOper--->举报聊天室');
              startReport(chatRoomServiceMember: chatRoomServiceMember);
            },
            blackSelectedFunc: (){
              startBlack(msgDataItem,chatRoomServiceMember);
            },
          );
        }
    );
  }
  showChatRoomOper() {
    showModalBottomSheet(
        context: Get.context,
        isScrollControlled: true,
        backgroundColor: ColorUtil.instance.color_transparent,
        builder: (BuildContext context){
          return ChatRoomOperWidget(
            isShowBlackOper: false,
            reportSelectedFunc: (){
              LogUtil.d('showChatRoomOper--->举报聊天室');
              startReport();
            },
          );
        }
    );
  }
//点击去人员首页
  void toPersonHome(dynamic userId) {
    NavigatorUtil.pushByName(RouteConfig.otherPersonHomePage,arguments: {
      'userId': '${userId}',
      'isFromOnlyChatRoom':true
    });
  }
  void startReport({UserEntity chatRoomServiceMember}) {
    // LoadUtil.showLoad(loadingText: '${StringUtil.instance.submiting}...');
    // Future.delayed(Duration(milliseconds: 500), ()=>LoadUtil.hideLoad());
    // ToastUtil.toast(StringUtil.instance.Report_Success);
    NavigatorUtil.pushByName(RouteConfig.reportPage,arguments: {
      'beBlockUid': '${(chatRoomServiceMember?.userId!=null)?chatRoomServiceMember?.userId:yxRoomId}'
    });
  }
  void getMyFollows() async{
    Map<String,dynamic> upData={
      "currentPage":1,
      "pageSize":100000,
      "type":3,
      // "keyword":"tp"
    };
    myFollowIds.clear();
    BaseEntity baseEntity = await moduleMyService.api_user_userFriend(parmsMap: upData);
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      List<UserEntity> myFollowTemps = baseEntity?.result??[];
      if(myFollowTemps.isNotEmpty)myFollowIds = myFollowTemps.map((e) => '${e?.userId}').toList();
      update();
    }
    update();
  }
  //查询我的拉黑用户列表
  void getMyBlacks() async{
    Map<String,dynamic> upData={
      "currentPage":1,
      "pageSize":100000,
    };
    myBlackIds.clear();
    BaseEntity baseEntity = await moduleMyService.api_user_blackList(parmsMap: upData);
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      List<UserEntity> myBlackTemps = baseEntity?.result??[];
      if(myBlackTemps.isNotEmpty)myBlackIds = myBlackTemps.map((e) => '${e?.userId}').toList();
      LogUtil.d('getMyBlacks--->myBlackIds=$myBlackIds');
    }
    update();
  }
  //拉黑
  void startBlack(NIMChatroomMessage msgDataItem,UserEntity chatRoomServiceMember) async{

    LoadUtil.showLoad(loadingText: '${StringUtil.instance.submiting}...');
    Map<String,dynamic> upData={
      "type": 1,
      "userId": chatRoomServiceMember?.userId,
      "yxAccid": chatRoomServiceMember?.yxAccid
    };
    BaseEntity baseEntity = await moduleMyService.api_user_BlackOrRemove(parmsMap: upData,
          isBlack: !isInBlackList(chatRoomServiceMember));
    LoadUtil.hideLoad();
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      //查询我的拉黑用户列表
      getMyBlacks();
    }else{
      ToastUtil.toast(baseEntity?.message);
    }
  }

  void startFollowOrUnfollow(NIMChatroomMessage msgDataItem, UserEntity chatRoomServiceMember) async{
    LoadUtil.showLoad(loadingText: '${StringUtil.instance.submiting}...');
    Map<String,dynamic> upData={
      "followUserId": chatRoomServiceMember?.userId
    };
    if(isFollow(chatRoomServiceMember)){
      upData['followType']=2;
    }else{
      upData['followType']=1;
    }
    BaseEntity baseEntity = await moduleMyService.api_user_followUser(parmsMap: upData);
    LoadUtil.hideLoad();
    if(baseEntity?.code == ApiConfig.SUCCESS_CODE){
      //重新获取关注的列表
      getMyFollows();
    }else{
      ToastUtil.toast(baseEntity?.message);
    }
  }
}
